import json

from haralyzer import HarParser, HarPage

# 打开并解析 HAR 文件
with open('novel.hctestedu.com_Archive.har', 'r', encoding='utf-8') as f:
    har_parser = HarParser(json.loads(f.read()))

# 获取所有页面（如果有多个）
pages = har_parser.pages

# 打印每个页面的请求信息
for page in pages:
    print(f"\n页面: {page.pageTimings['onContentLoad']}")

    # 遍历页面中的所有请求
    for entry in page.entries:
        print(f"\n请求: {entry.request['method']} {entry.request['url']}")
        print(f"状态码: {entry.response['status']}")
        print(f"响应时间: {entry.time} ms")
        print(f"响应大小: {entry.response['content']['size']} 字节")

        # 打印请求头
        print("\n请求头:")
        for header in entry.request['headers']:
            print(f"  {header['name']}: {header['value']}")

        # 打印响应头
        print("\n响应头:")
        for header in entry.response['headers']:
            print(f"  {header['name']}: {header['value']}")

        # 打印请求体（如果有）
        if 'postData' in entry.request and entry.request['postData'].get('text'):
            print("\n请求体:")
            print(entry.request['postData']['text'])

        # 打印响应体摘要（只打印前200个字符）
        if entry.response['content'].get('text'):
            print("\n响应体摘要:")
            print(entry.response['content']['text'][:200] + '...' if len(entry.response['content']['text']) > 200 else
                  entry.response['content']['text'])